package cn.qzc.service;

import cn.qzc.entiy.User;
import cn.qzc.mapper.UserMapper;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;

/**
 * Created by HP on 2019/5/8.
 */
@Service()
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public List<User> listUsers(){
        return userMapper.listUsers();
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    public int addUser(User user){
        String passwordHash =  passwordToHash(user.getPassword());
        user.setPassword(passwordHash);
        return userMapper.addUser(user);
    }

    /**
     * 根据Name获取用户
     * @param Name
     * @return
     */
    public User findByName(String Name) {
        return userMapper.getUser(new User(Name));
    }

    /**
     * 根据ID获取用户
     * @param id
     * @return
     */
    public User findById(Integer id){ return userMapper.getUser(new User(id));}

    /**
     * 删除用户
     * @param id
     * @return
     */
    public int delUser(Integer id){return userMapper.delUser(id);}

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    public User updateUser(User user){
        user.setId(findByName(user.getName()).getId());
        user.setPassword(passwordToHash(user.getPassword()));
        userMapper.updateUser(user);
        return findById(user.getId());
    }

    /**
     * 验证密码是否和数据库中的一致 Hash值比较
     * @param user  登陆对象
     * @param userInDataBase    数据库对象
     * @return
     */
    public boolean comparePassword(User user, User userInDataBase) {
        return passwordToHash(user.getPassword())      // 将用户提交的密码转换为 hash
                .equals(userInDataBase.getPassword()); // 数据库中的 password 已经是 hash，不用转换
    }

    /**
     * SHA-256
     * @param password
     * @returnx
     */
    private String passwordToHash(String password) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            digest.update(password.getBytes());
            byte[] src = digest.digest();
            StringBuilder stringBuilder = new StringBuilder();
            // 字节数组转16进制字符串
            // https://my.oschina.net/u/347386/blog/182717
            for (byte aSrc : src) {
                String s = Integer.toHexString(aSrc & 0xFF);
                if (s.length() < 2) {
                    stringBuilder.append('0');
                }
                stringBuilder.append(s);
            }
            return stringBuilder.toString();
        } catch (NoSuchAlgorithmException ignore) {
        }
        return null;
    }

    /*
   * JWT 形式的 token
   *
   */
    public String getToken(User user) {
        String token = "";
        Date expiresAt = new Date(System.currentTimeMillis() + 24L * 60L * 3600L * 1000L);
        try {
            token = JWT.create()
                    .withAudience(user.getId().toString())          // 将 user id 保存到 token 里面
                    .withIssuer("auth0")
                    .withClaim("name", user.getName())
                    .withExpiresAt(expiresAt)
                    .sign(Algorithm.HMAC256(user.getPassword()));   // 以 password 作为token 的密钥
        } catch (UnsupportedEncodingException ignore) {
        }
        return token;
    }
}
